package com.hyacinth.forumbite.service.impl;

import com.hyacinth.forumbite.common.AppResult;
import com.hyacinth.forumbite.common.ResultCode;
import com.hyacinth.forumbite.dao.UserMapper;
import com.hyacinth.forumbite.exception.ApplicationException;
import com.hyacinth.forumbite.model.User;
import com.hyacinth.forumbite.service.UserService;
import com.hyacinth.forumbite.utils.MD5Util;
import com.hyacinth.forumbite.utils.StringUtil;
import com.hyacinth.forumbite.utils.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author: Yun
 * @Date: 2025/5/20
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            // 打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 按照用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        if (existsUser != null) {
            log.info(ResultCode.AILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
        // 设置用户默认值
        Date date = new Date();
        user.setGender((byte) 2)
                .setArticleCount(0)
                .setIsAdmin((byte) 0)
                .setState((byte) 0)
                .setDeleteState((byte) 0)
                .setCreateTime(date)
                .setUpdateTime(date);


        int insert = userMapper.insert(user);
        if (insert != 1) {
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("用户新增成功 user: " + user.toString());
    }

    @Override
    public User selectByUserName(String username) {
        if (StringUtil.isEmpty(username)) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        // 参数校验
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(password)) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 查询用户
        User user = selectByUserName(username);
        if (user == null) {
            log.info("用户为空, username: " + username);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 校验密码 重点!
        // 数据库中的密码是加密后的,需要对用户输入的密码+盐 再进行加密 然后判断是否相等
        String encryptPassword = MD5Util.md5Salt(password, user.getSalt());
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.info("密码校验失败");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        // 登录成功
        log.info("登录成功");
        return user;
    }

    @Override
    public User selectById(Long id) {
        if (id == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn("user: id = " + id + ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser = new User()
                .setId(id)
                .setArticleCount(user.getArticleCount() + 1);
        int insert = userMapper.updateByPrimaryKeySelective(updateUser);
        if (insert < 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn("user: id = " + id + ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser = new User()
                .setId(id)
                .setArticleCount(user.getArticleCount() - 1);
        if (updateUser.getArticleCount() < 0) {
            updateUser.setArticleCount(0);
        }
        int insert = userMapper.updateByPrimaryKeySelective(updateUser);
        if (insert < 1) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if (user == null || user.getId() == null || user.getId() < 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User updateUser = new User()
                .setId(user.getId());
        if (!StringUtil.isEmpty(user.getUsername()) && !user.getUsername().equals(existsUser.getUsername())) {
            if (userMapper.selectByUserName(user.getUsername()) != null) {
                throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
        }
        if (user.getGender() != null) {
            if (user.getGender() < 0 || user.getGender() > 2) {
                updateUser.setGender((byte) 2);
            } else {
                updateUser.setGender(user.getGender());
            }
        }
        if (!StringUtil.isEmpty(user.getNickname())) {
            updateUser.setNickname(user.getNickname());
        }

        if (!StringUtil.isEmpty(user.getEmail())) {
            updateUser.setEmail(user.getEmail());
        }

        if (!StringUtil.isEmpty(user.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
        }
        if (!StringUtil.isEmpty(user.getRemark())) {
            updateUser.setRemark(user.getRemark());
        }

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPwd(Long id, String newPassword, String oldPassword) {
        if (id == null || id < 1 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询用户
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 验证旧密码是否正确
        String password = MD5Util.md5Salt(oldPassword, user.getSalt());
        if (!password.equalsIgnoreCase(user.getPassword())) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        // 重新生成盐, 对新密码进行加密
        String slat = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(newPassword, slat);
        User updateUser = new User()
                .setId(id)
                .setSalt(slat)
                .setPassword(encryptPassword)
                .setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }
}
